package cn.im.system;

import cn.im.util.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * IP统一过滤拦截
 */
public class IPInterceptor implements HandlerInterceptor {
    private static final Logger log= LoggerFactory.getLogger(IPInterceptor.class.getName());

    @Value("${TRAGET_IP}")
    public String targetIp;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤ip,若用户在白名单内，则放行
        String ipAddress= IPUtil.getIpAddr(request);
        log.info("request ip: {}",ipAddress);
        if(!targetIp.contains(ipAddress)){
//            log.info("request rejected, ip:{} ",ipAddress);
//            response.getWriter().append(String.format(consts.PATTERN_EXCEPTION,403,"request forbidden"));
//            return false;
            return  true;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
